package com.example.servlet.user;

import com.example.entity.Flight;
import com.example.entity.Order;
import com.example.entity.Ticket;
import com.example.entity.User;
import com.example.service.OperationService;
import com.example.service.UserService;
import com.example.service.impl.OperationServiceImpl;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@WebServlet("/user_ticket_operation")
public class uTicketOperationServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("application/json");
//        PrintWriter out = resp.getWriter();
        User user = (User) req.getSession().getAttribute("user");
        String ticketId = req.getParameter("ticketId");
        String flightId = req.getParameter("flightId");
        String actionType = req.getParameter("actionType");
        int f_id = Integer.parseInt(flightId);
        int t_id = Integer.parseInt(ticketId);

        LocalDateTime now = LocalDateTime.now();  // 获取当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 定义格式化模板
        String formattedNow = now.format(formatter);  // 格式化时间
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 定义格式化模板
        DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化今天的日期
        String formattedToday = today.format(formatterDate);

        Ticket ticket = service.getTicketById(t_id);
        try {
            switch (actionType) {
                case "cancel":
                    if(Objects.equals(ticket.getSeat_type(), "经济舱")) {
                        if(service.addEconomySpaceByFid(t_id)==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to add economy space");
                        }
                    }
                    else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                        if(service.addBusinessSpaceByFid(t_id)==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to add business space");
                        }
                    }
                    else {
                        if(service.addFirstSpaceByFid(t_id)==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to add first space");
                        }
                    }
                    if(service.cancelTicket(t_id)==0){
                        //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                        throw new Exception("Failed to cancel ticket");
                    }
                    if(service.getPassengersByOrderId(ticket.getOrder_id()) == 1) {
                        if(service.cancelOrder(ticket.getOrder_id(), formattedNow)==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to cancel order");
                        }
                    }else{
                        if(service.setOrderIdinTicket(t_id)==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to set order id in ticket");
                        }
                        if(service.reducePassengerOrderNumByPassengerId(user.getID_type(),user.getID_card())==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to reduce passenger order num");
                        }
                        if(service.reducePassengerPriceOrder(ticket.getOrder_id(), ticket.getPrice())==0){
                            //out.write("{\"success\": false, \"message\": \"取消失败\"}");
                            throw new Exception("Failed to reduce passenger price order");
                        }
                    }
                    service.commit();
                    break;
                case "reschedule":
                    resp.sendRedirect("user_reschedule_result?ticketId=" + ticketId);
                    return;
                case "refund":
                    if(Objects.equals(ticket.getSeat_type(), "经济舱")) {
                        if(service.addEconomySpaceByFid(f_id)==0){
                            throw new Exception("Failed to add economy space");
                        }
                    }
                    else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                        if(service.addBusinessSpaceByFid(f_id)==0){
                            throw new Exception("Failed to add business space");
                        }
                    }
                    else {
                        if(service.addFirstSpaceByFid(f_id)==0){
                            throw new Exception("Failed to add first space");
                        }
                    }
                    if(service.cancelTicket(t_id)==0){
                        throw new Exception("Failed to refund ticket");
                    }
                    Order order = service.getOrderById(ticket.getOrder_id());
                    User orderUser = service.getUserById(order.getUserId());
                    double refundMoney = ticket.getPrice();
                    if(Objects.equals(ticket.getStatusText(), "即将起飞")){
                        refundMoney = ticket.getPrice() * 0.7;
                    }
                    if(service.refundMoneyByUserIDtypeAndIDcard(orderUser.getID_type(),orderUser.getID_card(), refundMoney)==0){
                        throw new Exception("Failed to refund money");
                    }
                    if(service.getPassengersByOrderId(ticket.getOrder_id()) == 1) {
                        if(service.cancelOrder(ticket.getOrder_id(), formattedNow)==0){
                            throw new Exception("Failed to refund order");
                        }
                    }else{
                        if(service.setOrderIdinTicket(t_id)==0){
                            throw new Exception("Failed to set order id in ticket");
                        }
                        if(service.reducePassengerOrderNumByPassengerId(user.getID_type(),user.getID_card())==0){
                            throw new Exception("Failed to reduce passenger order num");
                        }
                        if(service.reducePassengerPriceOrder(ticket.getOrder_id(), ticket.getPrice())==0){
                            throw new Exception("Failed to reduce passenger price order");
                        }
                    }
                    service.commit();
                    break;
                case "rebook":
                    Flight flight = service.getFlightById(ticket.getFlightNo());
                    String departureCity = flight.getDeparture_city();
                    String arrivalCity = flight.getArrival_city();

                    String redirectUrl = "user_flight_search?" +
                            "departureCity=" + URLEncoder.encode(departureCity, StandardCharsets.UTF_8) +
                            "&arrivalCity=" + URLEncoder.encode(arrivalCity, StandardCharsets.UTF_8) +
                            "&departureDateStr=" + formattedToday;

                    resp.sendRedirect(redirectUrl);
                    return;
                default:
                    break;
            }
            resp.sendRedirect("user_ticket");
        } catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("ticket_operation_failure", new Object());
            resp.sendRedirect("user_ticket");
        }
    }
}
